﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EzDesk.DesktopClient
{
    using System.Windows;

    public class ThemeSelector : DependencyObject
    {

        public static readonly DependencyProperty CurrentThemeDictionaryProperty =
         DependencyProperty.RegisterAttached("CurrentThemeDictionary", typeof(Uri),
         typeof(ThemeSelector),
         new UIPropertyMetadata(null, CurrentThemeDictionaryChanged));

        public static Uri GetCurrentThemeDictionary(DependencyObject obj)
        {
            return (Uri)obj.GetValue(CurrentThemeDictionaryProperty);
        }

        public static void SetCurrentThemeDictionary(DependencyObject obj, Uri value)
        {
            obj.SetValue(CurrentThemeDictionaryProperty, value);
        }

        private static void CurrentThemeDictionaryChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            if(obj is FrameworkElement)
            {
                ApplyTheme(obj as FrameworkElement, GetCurrentThemeDictionary(obj));
            }
        }

        private static void ApplyTheme(FrameworkElement targetElement, Uri dictionaryUri)
        {
            if(targetElement == null)
                return;

            ThemeResourceDictionary themeDictionary = null;
            if(dictionaryUri != null)
            {
                themeDictionary = new ThemeResourceDictionary();
                themeDictionary.Source = dictionaryUri;

                targetElement.Resources.MergedDictionaries.Insert(0, themeDictionary);
            }

            List<ThemeResourceDictionary> existingDictionaries =
                (from dictionary in targetElement.Resources.MergedDictionaries.OfType<ThemeResourceDictionary>()
                 select dictionary).ToList();

            foreach(ThemeResourceDictionary thDictionary in existingDictionaries)
            {
                if(themeDictionary == thDictionary)
                    continue;
                targetElement.Resources.MergedDictionaries.Remove(thDictionary);
            }
        }
    }
    public class ThemeResourceDictionary : ResourceDictionary
    {
    }
}
